package com.fms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fms.dto.DeptAccess;
import com.fms.mapper.MenuCheckMapper;
import com.fms.mapper.SysDeptMapper;
import com.fms.entity.MenuCheck;
import com.fms.entity.SysDept;
import com.fms.service.MenuCheckService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
//菜单权限内容
public class MenuCheckServiceImpl extends ServiceImpl<MenuCheckMapper, MenuCheck> implements MenuCheckService {

    private final MenuCheckMapper menuCheckMapper;

    private final SysDeptMapper systemDeptMapper;
    //更新角色部门权限
    @Override
    public String updateAccess(DeptAccess deptAccess) {
        Long deptId;
        //更新数据
        if(deptAccess.getId() != null) {
            //组装部门数据
            deptId = deptAccess.getId();
            SysDept sysDept = new SysDept();
            sysDept.setId(deptId);
            sysDept.setName(deptAccess.getDeptName());
            //获取部门权限
            LambdaQueryWrapper<MenuCheck> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MenuCheck::getDeptId, deptId);
            //更新部门
            systemDeptMapper.updateById(sysDept);
            //删除部门数据
            menuCheckMapper.delete(queryWrapper);
        }
        //新增数据
        else {
            SysDept sysDept = new SysDept();
            sysDept.setName(deptAccess.getDeptName());
            systemDeptMapper.insert(sysDept);
            LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysDept::getName,deptAccess.getDeptName());
            SysDept newSysDept = systemDeptMapper.selectOne(queryWrapper);
            deptId = newSysDept.getId();
        }
        //保存角色权限数据
        List<Long> menuIds = deptAccess.getMenuIds();
        if (menuIds.contains(9L) || menuIds.contains(10L) || menuIds.contains(11L)){
            if (!menuIds.contains(7L)){
                menuIds.add(7L);
            }
        }
        if (menuIds.contains(7L)){
            if (!menuIds.contains(9L) && !menuIds.contains(10L) && !menuIds.contains(11L)){
                menuIds.add(9L);
                menuIds.add(10L);
                menuIds.add(11L);
            }
        }
        for (Long menuid : menuIds){
            MenuCheck check = new MenuCheck();
            check.setMenuId(menuid);
            check.setDeptId(deptId);
            menuCheckMapper.insert(check);
        }
        return "更改成功";
    }

    @Override
    public void deleteByDeptId(String id) {
        LambdaQueryWrapper<MenuCheck> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MenuCheck::getDeptId, id);
        menuCheckMapper.delete(queryWrapper);
    }
}
